package vn.csc.javafresher.xml.finalassignment.service;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

import vn.csc.javafresher.xml.finalassignment.entity.Guests;

public class XMLService {
	private File file;

	public XMLService(File file) {
		this.file = file;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}
	
	private Document readXMLFile() throws Exception {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document document = builder.parse(file);
		return document;
	}
	
	public ArrayList<String> getAllEmail() {
		Document document = null;
		try {
			document = readXMLFile();
		} catch (Exception e) {
			e.printStackTrace();
		}
		ArrayList<String> result = new ArrayList<String>();
		Element rootNode = (Element) document.getDocumentElement();
		NodeList emailList = rootNode.getElementsByTagName("email");
		for (int i = 0; i < emailList.getLength(); i++) {
			String email = ((Element) emailList.item(i)).getFirstChild().getTextContent();
			result.add(email);
		}
		return result;
	}
	
	public boolean isRegistered(String email, ArrayList<String> emailList) {
		for (String string : emailList) {
			if(string.endsWith(email)) {
				return true;
			}
		}
		return false;
	}
	
	public int newId() throws Exception {
		Document document = readXMLFile();
		Element rootNode = (Element) document.getDocumentElement();
		NodeList listNode = rootNode.getElementsByTagName("guest");
		Element lastNode = (Element) listNode.item(listNode.getLength() - 1);
		int id = Integer.parseInt(lastNode.getAttribute("id")) + 1;
		return id;
	}
	
	public boolean insertNewItem(String name, String email, String subscribe) {
		try {
			Document document = readXMLFile();
			Element rootNode = (Element) document.getDocumentElement();
			
			Element newGuest = document.createElement("guest");
			rootNode.appendChild(newGuest);
			
			newGuest.setAttribute("id", Integer.toString(newId()));
			
			Element date = document.createElement("date");
			Calendar calendar = Calendar.getInstance();
			SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			Text dateText = document.createTextNode(simpleFormat.format(calendar.getTime()));
			date.appendChild(dateText);
			newGuest.appendChild(date);
			
			Element nameElement = document.createElement("name");
			Text nameText = document.createTextNode(name);
			nameElement.appendChild(nameText);
			newGuest.appendChild(nameElement);
			
			Element emailElement = document.createElement("email");
			Text emailText = document.createTextNode(email);
			emailElement.appendChild(emailText);
			newGuest.appendChild(emailElement);
			
			Element surElement = document.createElement("subscribe");
			Text surText = document.createTextNode(subscribe);
			surElement.appendChild(surText);
			newGuest.appendChild(surElement);
	
			TransformerFactory factory = TransformerFactory.newInstance();
	        Transformer transformer = factory.newTransformer();

	        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

	        StringWriter sw = new StringWriter();
	        StreamResult result = new StreamResult(sw);
	        DOMSource source = new DOMSource(document);
	        transformer.transform(source, result);
	        String xmlString = sw.toString();

	        FileWriter fileWriter = new FileWriter(file, false);
	        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
	        bufferedWriter.write(xmlString);
	        bufferedWriter.flush();
	        bufferedWriter.close();
			return true;
		} catch(Exception e) {
			System.out.println(e.getMessage().toString());
			return false;
		}
	}
	
	public Guests getGuestList() throws Exception {
		JAXBContext jaxbContext = JAXBContext.newInstance(Guests.class);
		Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
		Guests guestList = (Guests) unmarshaller.unmarshal(new FileInputStream(file));
		return guestList;
	}
}
